import React, { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import SearchCategory from '../components/SearchCategory'; // 引入 SearchCategory 组件
import TopicResults from '../components/TopicResults'; // 引入话题结果组件
import PostResults from '../components/PostResults'; // 引入帖子结果组件
import UserResults from '../components/UserResults'; // 引入用户结果组件
import './SearchResults.css'
import { searchTopic, searchUser, searchPostBytime} from '../api/userApi'; // 根据你的文件路径调整

const SearchResults = () => {
  const [userId, setUserId] = useState(null);

  useEffect(() => {
    const storedUserId = localStorage.getItem('userId');
    if (storedUserId) {
      setUserId(storedUserId);
    }
  }, []);

  const location = useLocation();
  const query = new URLSearchParams(location.search).get('query'); // 获取 query 参数
  const [category, setCategory] = useState('topics');  // 默认类别为 'topics'
  const [results, setResults] = useState([]);

  useEffect(() => {
    if (!query) return;
  
    const fetchResults = async () => {
      try {
        let fetchedResults = [];
        switch (category) {
          case 'topics':
            fetchedResults = await searchTopic(query,userId); // 替换为实际的 userId
            break;
          case 'posts':
            fetchedResults = await searchPostBytime(query, userId); // 替换为实际的 userId
            break;
          case 'users':
            fetchedResults = await searchUser(query,userId); // 替换为实际的 userId
            break;
          default:
            fetchedResults = [];
        }
        setResults(fetchedResults); // 更新 results 状态
      } catch (error) {
        console.error('Error fetching search results:', error);
      }
    };
    fetchResults();  // 调用异步函数获取数据
  }, [query, category,userId]);  // 依赖于 query 和 category
  

  const handleCategoryChange = (newCategory) => {
    console.log("Category changed to:", newCategory);  // 调试：检查 category 的变化
    setCategory(newCategory);  // 更新类别
  };

  // 根据选中的 category 渲染不同的结果组件
  const renderResults = () => {
    switch (category) {
      case 'topics':
        // 渲染博客数据
        const topics = results.map((topic) => ({
          interestId: topic.interestId, 
          title: topic.name,
          description: topic.description, 
          image: topic.image,
          updateTime: topic.updateTime,
          count: topic.collectionCounts, 
          isBookmarked: topic.isCollected 
      }));
        return <TopicResults query={query} results={topics} />;
      case 'posts':
        const posts = results.map((blog) => ({
          userId:blog.userId,
          userImage: blog.userImage,
          blogImage: blog.blogImage,
          interestId:blog.interestId,
          blogId:blog.blogId,
          title: blog.name,
          author: blog.account,
          content: blog.description,
          time: blog.updateTime,
          likeCount: blog.likesCount,
          commentCount: blog.commentsCount,
          isLiked:blog.isLiked,
          isFollowed:blog.isFollowed,
          isCollected: blog.isCollected, 
        }));
        return <PostResults query={query} results={posts} />;
      case 'users':
        return <UserResults query={query} results={results} />;
      default:
        return null;
    }
  };

  return (
    <div style={{ display: 'flex' }} className='results'>
      <SearchCategory category={category} onCategoryChange={handleCategoryChange} className='results-left' />

      <div className='results-right'>
        {query ? (
          <>
            {renderResults()}  {/* 根据选中的类别渲染相应的组件 */}
          </>
        ) : (
          <p>请输入搜索内容</p>
        )}
      </div>
    </div>
  );
};

export default SearchResults;